/*******************************************************************************
 * Copyright (c) 2007, Geophysical Center RAS
 * Sergey Berezin, Dmitry Voitsekhovskiy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * - Neither the name of the Geophysical Center RAS nor the names
 * of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

namespace VisualEsse.DataEngine
{
    /// <summary>Composite key to index files in cache</summary>
    public class CacheKey
    {

        protected object[] keys;

        public CacheKey()
        {
            // Nothing to do here...
        }

        public CacheKey(params object[] ks)
        {
            keys = (object[])ks.Clone();
        }

        [XmlElement(ElementName = "key")]
        public object[] Keys
        {
            get
            {
                return keys;
            }
            set
            {
                keys = (object[])value.Clone();
            }
        }

        public override int GetHashCode()
        {
            int hashcode = 0;
            if (keys != null)
                foreach (object key in keys)
                    hashcode ^= key.GetHashCode();
            return hashcode;
        }

        public override bool Equals(object obj)
        {
            if (obj is CacheKey)
            {
                CacheKey key2 = (CacheKey)obj;
                if (keys == null)
                    return (key2.keys == null);
                if (key2.keys == null)
                    return false;
                if (keys.Length != key2.keys.Length)
                    return false;
                for (int i = 0; i < keys.Length; i++)
                    if (!keys[i].Equals(key2.keys[i]))
                        return false;
                return true;
            }
            else
                return false;
        }
    }

    /// <summary>Class to access files in cache. It is derived from files stream.
    /// When stream is closed, size of associated cache is updated. This is used
    /// to keep cache size in specified limits</summary>
    public class CacheStream : FileStream
    {
        protected ICache cache;
        protected CacheKey key;

        public CacheStream(ICache cache, CacheKey key, FileMode mode, FileAccess access)
            : base(cache.GetFileName(key, true), mode, access)
        {
            this.cache = cache;
            this.key = key;
        }

        public override void Close()
        {
            if (cache != null)
                cache.UpdateFile(key, Length);
            base.Close();
        }
    }

    /// <summary>Represents one record in cache file list. Contains file name in cache,
    /// current files size and last access time (to implement LRU algorithm)</summary>
    public class CacheFile
    {
        /// <summary>Name of file in cache</summary>
        protected string name;
        /// <summary>Last access time</summary>
        protected DateTime time;
        /// <summary>Size of file in bytes</summary>
        protected long size;

        public CacheFile()
        {
            // Nothing to do here ...
        }

        public CacheFile(string name)
        {
            this.name = name;
            size = 0;
            time = DateTime.Now;
        }

        [XmlElement(ElementName = "name")]
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        [XmlElement(ElementName = "accessTime")]
        public DateTime AccessTime
        {
            get
            {
                return time;
            }
            set
            {
                time = value;
            }
        }

        [XmlElement(ElementName = "size")]
        public long Size
        {
            get
            {
                return size;
            }
            set
            {
                size = value;
            }
        }

        public void UpdateAccessTime()
        {
            time = DateTime.Now;
        }
    }

    public interface ICache : IDisposable
    {
        string Folder { get; }
        string GetFileName(CacheKey key, bool updateTime);

        System.IO.Stream OpenFile(CacheKey key, System.IO.FileAccess access);
        System.IO.Stream CreateFile(CacheKey key, System.IO.FileAccess access);
        System.IO.Stream OpenOrCreateFile(CacheKey key, System.IO.FileAccess access);

        void UpdateFile(CacheKey key, long newLength);
        void CompressCache();
    }
}
